<template>
    <div class="maintainexploitconfigtab" v-loading="state.loading">
        <el-card>
            <template #header>
				<div class="card-header clearfix">
                        <span class="headerTitle">{{router.currentRoute.value.meta.title}}</span>
                        <div class="floatRight">
                            <el-button type="primary" v-if="isAuthBtn('add')" @click="tabBtn('add','')"><i class="fa fa-send"></i>新增</el-button>
                        </div>
				</div>
            </template>
            <div>
                <el-table
                    :data="state.dataList"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="id"
                >
                    <el-table-column prop="id" label="id"  align="center" min-width="100" />
                    <el-table-column prop="title" label="配置名称"  align="center"  min-width="200" />
                    <el-table-column prop="fields" label="配置字段"  align="center" min-width="200"  />
                    <el-table-column prop="type" label="配置类型"  align="center" min-width="200"  />
                    <el-table-column label="值"  align="center"  min-width="100" >
                        <template #default="scope">
                            <div v-if="scope.row.value">
                                <div class="k-line-2" v-if="scope.row.type=='text'||scope.row.type=='textarea'">
                                    {{scope.row.value}}
                                </div>
                                <div v-if="scope.row.type=='upload'">
                                    <div v-if="scope.row.input_type=='image'">
                                        <el-image style="width: 100px;height: 100px;" fit="cover" :src="scope.row.upload_type=='1'?scope.row.value:scope.row.value[0]" preview-teleported  :preview-src-list="scope.row.upload_type=='1'?[scope.row.value]:scope.row.value">
                                            <template #error>
                                                <div style="line-height: 150px;text-align: center;">
                                                    暂无图片
                                                </div>
                                            </template>
                                        </el-image>
                                    </div>
                                </div>
                                <div v-if="scope.row.type=='radio'">
                                    {{scope.row.parameterList[scope.row.value]}}
                                </div>
                                <div v-if="scope.row.type=='rich'">
                                    <div class="k-line-2" v-html="scope.row.value"></div>
                                </div>
                                <div v-if="scope.row.type=='json'">
                                    {{JSON.stringify(scope.row.value)}}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否显示" align="center"  min-width="100" >
                        <template #default="scope">
                            <el-switch
                                v-model="scope.row.isshowT"
                                class="ml-2"
                                width="60"
                                inline-prompt
                                active-text="显示"
                                inactive-text="隐藏"
                                @change="tabBtn('isshowT',scope.row)"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="200" align="center">
                        <template #default="scope">
                            <el-button link type="primary" v-if="isAuthBtn('editor')" @click="tabBtn('editor',scope.row)">编辑</el-button>
                            <el-button link type="primary" v-if="isAuthBtn('del')" @click="tabBtn('del',scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
         <!-- 修改弹窗 -->
		<el-dialog
            v-model="state.upShow"
            :title="state.detailData.id?'修改配置信息':'新增配置信息'"
            center
            width="80%"
        >
        <div v-if="state.upShow">
            <el-form :model="state.detailData" ref="detailDataRef" :rules="rules" label-width="180px" status-icon>
                <el-tabs v-model="state.detailData.type">
                    <el-tab-pane v-for="(item, index) in state.typeList" :key="index" :label="item.title" :name="item.key"></el-tab-pane>
                </el-tabs>
                <el-form-item label="配置分类" prop="config_tab_id" >
                    <el-select v-model="state.detailData.config_tab_id" filterable placeholder="请选择分类">
                        <el-option
                        v-for="item in state.tabList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置类型" prop="input_type" v-if="state.detailData.type=='text'">
                    <el-select v-model="state.detailData.input_type" filterable placeholder="请选择类型">
                        <el-option
                        v-for="item in state.inputTypeList"
                        :key="item.key"
                        :label="item.title"
                        :value="item.key"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置类型" prop="input_type" v-if="state.detailData.type=='upload'">
                    <el-select v-model="state.detailData.input_type" filterable placeholder="请选择类型">
                        <el-option
                        v-for="item in state.inputTypeListu"
                        :key="item.key"
                        :label="item.title"
                        :value="item.key"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置名称" prop="title" >
                    <el-input v-model="state.detailData.title" clearable />
                </el-form-item>
                <el-form-item label="配置字段(英文)" :prop="state.detailData.id?'':'fields'" >
                    <el-input v-model="state.detailData.fields" :disabled="state.detailData.id?true:false" clearable />
                </el-form-item>
                <el-form-item label="配置简介" prop="desc" >
                    <el-input type="textarea"  v-model="state.detailData.desc" clearable />
                </el-form-item>
                <el-form-item label="上传类型" prop="upload_type" v-if="state.detailData.type=='upload'">
                    <el-radio-group v-model="state.detailData.upload_type" class="ml-4">
                      <el-radio label="1" size="large">单图</el-radio>
                      <el-radio label="2" size="large">多图</el-radio>
                    </el-radio-group>                    
                </el-form-item>
                <el-form-item label="配置参数" prop="parameter" v-if="state.detailData.type=='radio'||state.detailData.type=='checkbox'||state.detailData.type=='json'">
                    <el-input type="textarea" placeholder="参数方式例如:
1=>男
2=>女
3=>保密" v-model="state.detailData.parameter" clearable />
                </el-form-item>
                <el-form-item label="配置内容" prop="value" >
                    <div v-if="state.detailData.type=='text'" style="width: 100%;">
                        <div v-if="state.detailData.input_type=='input'">
                            <el-input v-model="state.detailData.value" clearable />
                        </div>
                        <div v-if="state.detailData.input_type=='number'">
                            <el-input-number v-model="state.detailData.value"  />
                        </div>
                        <div v-if="state.detailData.input_type=='time'">
                            <el-time-picker
                                v-model="state.detailData.value"
                                arrow-control
                            />
                        </div>
                        <div v-if="state.detailData.input_type=='color'">
                            <el-color-picker v-model="state.detailData.value" show-alpha />
                        </div>
                    </div>
                    <div v-else-if="state.detailData.type=='textarea'" style="width: 100%;">
                        <el-input type="textarea"  v-model="state.detailData.value" clearable />
                    </div>
                    <div v-else-if="state.detailData.type=='rich'" style="width: 100%;">
                        <Editor  v-model:get-html="state.detailData.value"  />
                    </div>
                    <div v-else-if="state.detailData.type=='radio'||state.detailData.type=='checkbox'" style="width: 100%;">
                        <div v-if="state.detailData.parameterList">
                            <el-select v-model="state.detailData.value" filterable placeholder="请选择" :multiple="state.detailData.type=='radio'?false:true">
                                <el-option
                                v-for="item,key in state.detailData.parameterList"
                                :key="key"
                                :label="item"
                                :value="key"
                                />
                            </el-select>
                        </div>
                        <div v-else>
                            <el-input v-model="state.detailData.value" clearable />
                        </div>
                    </div>
                    <div v-else-if="state.detailData.type=='upload'" style="width: 100%;">
                        <div v-if="state.detailData.input_type=='image'">
                            <div v-if="state.detailData.upload_type=='1'">
                                <div class="selectImg">
                                    <el-image style="width: 100%;height: 100%;" fit="cover" :src="state.detailData.value">
                                        <template #error>
                                            <div style="line-height: 150px;text-align: center;">
                                                暂无图片
                                            </div>
                                        </template>
                                    </el-image>
                                    <div class="imgBtn">
                                        <i class="fa fa-eye" v-if="state.detailData.value"  @click="selectBtn('eye','1')"></i>
                                        <i class="fa fa-trash-o selectDel" v-if="state.detailData.value"  @click="selectBtn('del','1')"></i>
                                        <i class="fa fa-file-image-o" v-if="!state.detailData.value" @click="selectBtn('select','1')"></i>
                                    </div>
                                </div>
                            </div>
                            <div v-if="state.detailData.upload_type=='2'">
                                <div class="imgItem">
                                    <draggable item-key="index" :list="state.detailData.value" animation="300" >
                                        <template #item="{ element }">
                                            <div class="selectImg">
                                                <el-image style="width: 100%;height: 100%;" fit="cover" :src="element">
                                                    <template #error>
                                                        <div style="line-height: 150px;text-align: center;">
                                                            暂无图片
                                                        </div>
                                                    </template>
                                                </el-image>
                                                <div class="imgBtn">
                                                    <i class="fa fa-eye" v-if="state.detailData.value"  @click="selectBtn('eye','1',element)"></i>
                                                    <i class="fa fa-trash-o selectDel" v-if="state.detailData.value"  @click="selectBtn('del','1',element)"></i>
                                                </div>
                                            </div>
                                        </template>
                                    </draggable>
                                </div>
                                <div class="imgItem">
                                    <div class="k-col-center k-row-center" style="padding:20px;display:flex;height: 150px;">
                                        <!-- <i class="fa fa-file-image-o"  @click="selectImgBtn('select',item)"></i> -->
                                        <el-button type="primary" plain @click="selectBtn('select','1')">选择图片</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else-if="state.detailData.input_type=='video'||state.detailData.input_type=='audio'||state.detailData.input_type=='file'">
                            <div v-if="state.detailData.upload_type=='1'">
                                <div class="selectImg">
                                    <el-image style="width: 100%;height: 100%;" fit="cover" :src="state.detailData.value.imgurl">
                                        <template #error>
                                            <div style="line-height: 150px;text-align: center;">
                                                暂无图片
                                            </div>
                                        </template>
                                    </el-image>
                                    <div class="imgBtn">
                                        <i class="fa fa-eye" v-if="state.detailData.value"  @click="selectBtn('eye','5')"></i>
                                        <i class="fa fa-trash-o selectDel" v-if="state.detailData.value"  @click="selectBtn('del','5')"></i>
                                        <i class="fa fa-file-image-o" v-if="!state.detailData.value" @click="selectBtn('select','5')"></i>
                                    </div>
                                </div>
                            </div>
                            <div v-if="state.detailData.upload_type=='2'">
                                <div class="imgItem">
                                    <draggable item-key="index" :list="state.detailData.value" animation="300" >
                                        <template #item="{ element }">
                                            <div class="selectImg">
                                                <el-image style="width: 100%;height: 100%;" fit="cover" :src="element.imgurl">
                                                    <template #error>
                                                        <div style="line-height: 150px;text-align: center;">
                                                            暂无图片
                                                        </div>
                                                    </template>
                                                </el-image>
                                                <div class="imgBtn">
                                                    <i class="fa fa-eye" v-if="state.detailData.value"  @click="selectBtn('eye','5',element)"></i>
                                                    <i class="fa fa-trash-o selectDel" v-if="state.detailData.value"  @click="selectBtn('del','5',element)"></i>
                                                </div>
                                            </div>
                                        </template>
                                    </draggable>
                                </div>
                                <div class="imgItem">
                                    <div class="k-col-center k-row-center" style="padding:20px;display:flex;height: 150px;">
                                        <!-- <i class="fa fa-file-image-o"  @click="selectImgBtn('select',item)"></i> -->
                                        <el-button type="primary" plain @click="selectBtn('select','5')">选择图片</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else>
                            <el-input v-model="state.detailData.value" clearable />
                        </div>
                    </div>
                    <div v-else-if="state.detailData.type=='json'" style="width: 100%;"> 
                        <el-row :gutter="20" v-for="it,int in state.detailData.value" :key="int" v-if="state.detailData.parameterList">
                            <el-col :span="parseInt(20/Object.values(state.detailData.parameterList).length)" v-for="im,i in state.detailData.parameterList" :key="i">
                                <el-input v-model="state.detailData.value[int][i]" :placeholder="im" />
                            </el-col>
                            <el-col :span="4">
                                <el-button type="success" @click="jsonBtn('add',state.detailData.value)" circle v-if="int==0"><i class="oneIcon fa fa-plus"></i></el-button>
                                <el-button type="primary" @click="jsonBtn('move',state.detailData.value,int,int+1)" circle v-if="(int+1)!=state.detailData.value.length"><i class="oneIcon fa fa-angle-down"></i></el-button>
                                <el-button type="warning" @click="jsonBtn('move',state.detailData.value,int,int-1)" circle v-if="int!=0"><i class="oneIcon fa fa-angle-up"></i></el-button>
                                <el-button type="danger"  @click="jsonBtn('del',state.detailData.value,int)" circle><i class="oneIcon fa fa-trash"></i></el-button>
                            </el-col>
                        </el-row>
                        <div v-if="!state.detailData.value||state.detailData.value.length<=0">
                            <el-button type="success" @click="jsonBtn('add',state.detailData.value)" circle><i class="oneIcon fa fa-plus"></i></el-button>
                        </div>
                    </div>
                    <div v-else style="width: 100%;"> 
                        <el-input type="textarea"  v-model="state.detailData.value" clearable />
                    </div>
                </el-form-item>
                <el-form-item label="验证规则" prop="required" >
                    <el-input v-model="state.detailData.required" placeholder="多个请用,隔开例如：required:true,url:true" clearable />
                </el-form-item>
                <el-form-item label="多行文本高(行)" prop="high" v-if="state.detailData.type=='textarea'">
                    <el-input-number v-model="state.detailData.high" clearable />
                </el-form-item>
                <el-form-item label="排序" prop="order_num" >
                    <el-input-number v-model="state.detailData.order_num" clearable />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.upShow = false;state.btnloading=false;">取消</el-button>
                    <el-button type="primary" @click="queding" :loading="state.btnloading" :disabled="state.btnloading">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!--附件弹窗-->
		<el-dialog
            v-model="state.selectImgShow"
            title="选择附件"
            center
            width="80%"
            append-to-body
        >
            <Accessory v-if="state.selectImgShow" :type="state.fileType" @select="fileSelectBtn"></Accessory>
        </el-dialog>
        <el-dialog v-model="imageShow">
            <img style="width:100%;" :src="imageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
    
<script lang="ts" setup name="maintainexploitconfigtab">
    import { toRefs,ref, reactive,onMounted, defineComponent,defineAsyncComponent } from 'vue';
    import { useRouter } from 'vue-router'
    import { ElNotification, ElMessage ,ElMessageBox ,FormRules,ElTree} from 'element-plus'
    import { systemApi } from '/@/api';
    import Editor from '/@/components/editor/index.vue';
    import draggable from 'vuedraggable' //拖拽
    import { isModification } from '/@/utils/kingmin';//去重
    // 引入组件
    const Accessory= defineAsyncComponent(() => import('/@/components/accessory/index.vue'));
    const router = useRouter();
    const imageUrl = ref('')
    const imageShow = ref(false)
    const detailDataRef=ref();
    const state = reactive({
        roleBtn:router.currentRoute.value.meta.roleBtn,
        btnloading:false,
        loading:true,
        dataList:[],
        pages: {
            isAll: false,
            pageCount: 0,
            pageSize: 10,
            recordCount: 0,
            pno: 1
          },
        tabData:{},
        originalData:{},
        upShow:false,
        detailData:{},
        tabList:[],
        typeList:[
            {"key":"text","title":"文本框"},
            {"key":"textarea","title":"多行文本框"},
            {"key":"rich","title":"富文本"},
            {"key":"radio","title":"单选框"},
            {"key":"checkbox","title":"多选框"},
            {"key":"upload","title":"文件上传"},
            {"key":"json","title":"数据类型"},
        ],
        inputTypeList:[
            {"key":"input","title":"文本框"},
            {"key":"time","title":"时间"},
            {"key":"color","title":"颜色"},
            {"key":"number","title":"数字"},
        ],
        inputTypeListu:[
            {"key":"image","title":"图片"},
            {"key":"video","title":"视频"},
            {"key":"audio","title":"音频"},
            {"key":"file","title":"文件"},
        ],
        fileType:'1',
        selectImgShow:false,
    });
    const rules = reactive<FormRules>({
        config_tab_id: [
            { required: true, message: '请选择分类信息', trigger: ['blur', 'change'] },
        ],
        title: [
            { required: true, message: '请填写配置名称', trigger: ['blur', 'change'] },
            { min: 2, max:12, message: '最少2个字符,最多12个字符', trigger: ['blur', 'change'] },
        ],
        fields: [
            { required: true, message: '请填写配置字段', trigger: ['blur', 'change'] },
            { min: 4,  message: '最少4个字符 ', trigger: ['blur', 'change'] },
        ],
        upload_type: [
            { required: true, message: '请选择上传的类型', trigger: ['blur', 'change'] },
        ],
        order_num: [
            { required: true, message: '请填写配置排序', trigger: ['blur', 'change'] },
        ]
        
    });
    const jsonBtn=(e:string,item:object,i:number,i2:number)=>{
        if(e=='add'){
            let a={};
            for(let k in state.detailData.parameterList){
                a[k]="";
            }
            state.detailData.value.push(a);
        }
        if(e=='del'){
            state.detailData.value.splice(i, 1);
        }
        if(e=='move'){
            state.detailData.value[i]=state.detailData.value.splice(
            i2,
            1,
            state.detailData.value[i]
            )[0]
        }
    }
    const selectBtn=(e:string,t:string,i:string)=>{
        if(t=='1'){
            if(e=='eye'){
                if(i){
                    imageUrl.value = state.detailData.value[state.detailData.value.indexOf(i)]
                }else{
                    imageUrl.value = state.detailData.value
                }
                imageShow.value = true
            }
        }else{
            if(e=='eye'){
                if(i){
                //     imageUrl.value = state.detailData.value[state.detailData.value.indexOf(i)]
                    tourl(i.url,1);
                }else{
                //     imageUrl.value = state.detailData.value
                    tourl(state.detailData.value.url,1);
                }
                // imageShow.value = true
            }
        }
        if(e=='del'){
            if(i){
                let d=[];
                for(let j in state.detailData.value){
                    if(state.detailData.value[j]!=i){
                        d.push(state.detailData.value[j]);
                    }
                }
                state.detailData.value=d;
            }else{
                state.detailData.value="";
            }
        }
        if(e=='select'){
            if(t=='5'){
                if(state.detailData.input_type=='video'){
                    t='2';
                }
                if(state.detailData.input_type=='audio'){
                    t='3';
                }
                if(state.detailData.input_type=='file'){
                    t='4';
                }
            }
            console.log(t)
            state.fileType=t;
            state.selectImgShow=true;
        }
    }
    const fileSelectBtn=(item)=>{
        console.log(item)
        for(let p of item){
            if(state.detailData.input_type=='image'){
                if(state.detailData.upload_type=='1'){
                    state.detailData.value=p.url;
                }else{
                    if(state.detailData.value.constructor !== Array){
                        state.detailData.value=[];
                    }
                    state.detailData.value.push(p.url);
                }
            }else{
                let f={
                    url:p.url,
                    imgurl:p.imgurl,
                    name:p.fname,
                    id:p.id,
                }
                if(state.detailData.upload_type=='1'){
                    state.detailData.value=f;
                }else{
                    if(state.detailData.value.constructor !== Array){
                        state.detailData.value=[];
                    }
                    state.detailData.value.push(f);
                }
            }
        }
        state.selectImgShow=false;
    }
    const queding=()=>{
        detailDataRef.value.validate((valid) => {
            if (valid) {
                // 修改
                let data=JSON.parse(JSON.stringify(state.detailData));
                state.btnloading=true;
                let dt={};
                if(state.detailData.id){
                    dt=isModification(data,state.originalData);
                    // let dt=state.detailData;
                    if(Object.values(dt).length>0){
                        dt.fields=state.detailData.fields;
                    }else{
                        ElMessage({message:'没有要修改的数据',type:"warning"});
                        state.upShow=false;
                        state.btnloading=false;
                        return false;
                    }
                    // console.log(dt)
                    upDataFun(dt);
                }else{
                    // console.log(data)
                    addDataFun(data);
                    
                }			
            }
        })
    }
    // 操作按钮
    const tabBtn=(e:string,item:object)=>{
        if(e=='del'){
            ElMessageBox.confirm(
                '确定删除配置信息['+item.title+']吗?',
                '提示',
                {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
                }
            )
            .then(() => {
                let dt={
                    fields:item.fields,
                    isdel:1
                }
                upDataFun(dt);
                //  console.log(dt)
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
        }
        if(e=='editor'){
            if(state.tabList.length<=0){
                getTabList();
            }
            state.detailData=JSON.parse(JSON.stringify(item));
            state.originalData=JSON.parse(JSON.stringify(item));
            state.upShow=true;
        }
        if(e=='add'){
            if(state.tabList.length<=0){
                getTabList();
            }
            state.detailData={
                id:"",
                fields:"",
                type:"text",
                input_type:"input",
                config_tab_id:router.currentRoute.value.params.id,
                parameter:'',
                upload_type:'',
                required:'',
                high:0,
                value:'',
                title:"",
                desc:"",
                isshow:'1',
                order_num:100
            };
            state.upShow=true;
        }
        if(e=='isshowT'){
            // console.log(item.isshowT)
            let dt={
                isshow:item.isshowT?'0':'1',
                fields:item.fields
            }
            upDataFun(dt);
        }
    }
    // 获取系统配置顶级分类
    const getTabList=()=>{
        systemApi('oneConfigTab?isAll=1',{}).then((res)=>{
            state.tabList=res;
            // getConfigData();

        })
    }
    // 修改
    const upDataFun=(dt:object)=>{
        if(!dt){
            ElMessage.error('修改的数据为空');
            return false;
        }
        systemApi('upConfig',dt).then(res=>{
            ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
            state.upShow=false;
            state.btnloading=false;
            getConfigData();
        })
        .catch(res=>{
            if(res.code!=450000){
                ElMessageBox.confirm(res.msg, '提示', {
                    confirmButtonText: '确定1',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {})
                .catch(() => {});
                state.btnloading=false;
            }
        })
    }
    // 新增
    const addDataFun=(dt:object)=>{
        if(!dt){
            ElMessage.error('新增的数据为空');
            return false;
        }
        systemApi('addConfig',dt).then(res=>{
            ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
            state.upShow=false;
            state.btnloading=false;
            getConfigData();
        })
        .catch(res=>{
            if(res.code!=450000){
                ElMessageBox.confirm(res.msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {})
                .catch(() => {});
                state.btnloading=false;
            }
        })
    }
    // 获取系统设置分类
    const getConfigData=()=>{
        systemApi('configDetail?id='+router.currentRoute.value.params.id,{}).then((res)=>{
            state.dataList=res.list;
            state.tabData=res.tab;
            router.currentRoute.value.meta.title=res.tab.title;
            state.loading=false;
            // getConfigData();

        })
    }
    // 权限判断
    const isAuthBtn = (e) => {
        let auth=false;
        if(e){
            for(let p of state.roleBtn){
                if(p==e){
                    auth=true;
                }
            }
        }
        return auth;
    };
    // 跳转
  // 跳转
    const tourl = (e,iswb) => {
        if(iswb){
            window.open(e);
        }else{
            router.push(e);
        }
    };
    onMounted(()=>{
          // 获取当前路由实例参数
          console.dir(router.currentRoute.value.params);
        //   console.dir(router.currentRoute.value.meta.roleBtn);
          if(!isAuthBtn('index')){
              router.push('/401');
          }else{
              //操作函数
              getConfigData();
          }
    })
</script>
    
<style scoped lang="scss">
    .maintainexploitconfigtab{
        padding:5px;
        .imgItem{
            display: inline-block;
            vertical-align: bottom;
        }
        .el-row {
            margin-bottom: 20px;
        }
    }
</style>
    